import {AxdrType} from "../asn1.axdr/AxdrType";
import {ReverseByteArrayInputStream} from "../ReverseByteArrayInputStream";
import {ReverseByteArrayOutputStream} from "../ReverseByteArrayOutputStream";
import {Buffer} from "buffer";
import {AxdrEnum} from "../asn1.axdr/AxdrEnum";
import {AxdrOptional} from "../asn1.axdr/AxdrOptional";
import {SecurityData} from "./SecurityData";


export class ConnectResponseInfo implements AxdrType{

    dataCode : Buffer | null = null;
    connectResult : AxdrEnum | null = null;
    securityData : AxdrOptional<SecurityData> = new AxdrOptional<SecurityData>(new SecurityData(), false);

    constructor() {
    }

    set_dataCode(dataCode : Buffer){
        this.dataCode = dataCode;
    }

    set_all(connectResult : AxdrEnum, securityData : SecurityData){
        this.connectResult = connectResult;
        this.securityData.setValue(securityData);
    }

    decode(input: ReverseByteArrayInputStream): number {
        let codeLength = 0;

        this.connectResult = new AxdrEnum();
        this.connectResult.set_const();
        codeLength += this.connectResult.decode(input);

        this.securityData = new AxdrOptional<SecurityData>(new SecurityData(), false);
        codeLength += this.securityData.decode(input);

        return codeLength;
    }

    encode(output: ReverseByteArrayOutputStream): number {
        let codeLength;

        if (this.dataCode != null) {
            codeLength = this.dataCode.length;
            for (let i = this.dataCode.length - 1; i >= 0; i--) {
                output.write(this.dataCode[i]);
            }
        } else {
            if(this.connectResult != null && this.securityData != null){
                codeLength = 0;
                codeLength += this.securityData.encode(output);
                codeLength += this.connectResult.encode(output);
            }else{
                throw new Error("securityData or connectResult is null");
            }
        }
        return codeLength;
    }

    ncodeAndSave(encodingSizeGuess: number) {
        let revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = revOStream.getArray();
    }

    toString(): string {
        if (this.securityData != null && this.connectResult != null) {
            return "sequence: {"+ "connectResult: " + this.connectResult + ", securityData: " + this.securityData  + "}";
        } else {
            return "securityData || connectResult is null ";
        }
    }

}
